package racer.client.gui;

import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import javax.imageio.ImageIO;

import java.util.HashMap;



public class ImageBank {
	
	private final static String DEFAULT_THEME = "street";
	
	private String images_path = "images";
	private String themes_path = "images/themes";
	
    private static HashMap<String,BufferedImage> images;
    
	public ImageBank() {
		System.out.println("Listing images files and directories");
		images = new HashMap<String,BufferedImage>();
		loadImages(new File(images_path));
		loadImages(new File(themes_path + "/" + DEFAULT_THEME));
	}
	
	public ImageBank(String theme) {
		System.out.println("Listing images files and directories");
		images = new HashMap<String,BufferedImage>();
		loadImages(new File(images_path));
		loadImages(new File(themes_path + "/" + theme));
	}
	
	// recursively loads all images in root -and subdirectories
	// small change: not recursive for the moment, just call method for each directory you want the images of
	private void loadImages(File file) {
		
		if (file.isDirectory()) {
			String[] children = file.list();
			for (int i=0; i<children.length; i++) {
				File f = new File(file, children[i]);
				if(f.isFile())
					loadImages(f);
			}
		}
		if(file.isFile() && !file.isHidden()) {
			int ext_pos = file.getName().lastIndexOf(".");
			if (ext_pos == -1) {
				return;
			}
			
			String filename = file.getName().substring(0, ext_pos);
			String extension = file.getName().substring(ext_pos+1);		
			
			//TODO instead of looking to extension, find out real file type through e.g. FileView.getTypeDescription(File f)
			//TODO put usable extensions in some sort of list
			//TODO at this moment there are files with same filename but different extension
			if(extension.equals("png") || extension.equals("PNG") || extension.equals("jpg") || 
					extension.equals("JPG") || extension.equals("jpeg") || extension.equals("JPEG") || 
					extension.equals("gif") || extension.equals("GIF")) {
				System.out.println(file.getAbsolutePath());
				try {
					BufferedImage im = ImageIO.read(file);
					images.put(filename, im);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static BufferedImage getImage(String key) {
		return images.get(key);
	}
}
